package com.doudou.oauth.provider;

import com.doudou.oauth.token.AccessTokenRemoteAuthenticationToken;
import lombok.Setter;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * @author 傻男人
 * @date 2020-05-08 22:47
 * @describe
 */
public class AccessTokenRemoteAuthenticationProvider implements AuthenticationProvider {

    @Setter
    TokenStore tokenStore;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        AccessTokenRemoteAuthenticationToken token = (AccessTokenRemoteAuthenticationToken)authentication;

        OAuth2Authentication auth2Authentication = tokenStore.readAuthentication(token.getToken());

        if(auth2Authentication == null){
            throw  new BadCredentialsException("token 认证失败");
        }

        return auth2Authentication;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return AccessTokenRemoteAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
